package rad.framework.web;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rad.framework.jpa.JpaUtil;
import rad.framework.lang.ExceptionUtil;
import rad.framework.validator.ValidationUtil;

import org.hibernate.validator.InvalidValue;

public class ValidationServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String LINE = "------------------------------------";

	public ValidationServlet() {
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			String persistenceUnitJndiName = getInitParameter("persistenceUnitJndiName");
			response.getOutputStream().println("Started: " + new Date());

			Set<String> classes = JpaUtil
					.getEntityNames(persistenceUnitJndiName);
			for (String className : classes) {
				try {
					Map<String, InvalidValue[]> errors = ValidationUtil
							.validateAll(persistenceUnitJndiName, className);
					Set<String> keys = errors.keySet();
					for (String key : keys) {
						response.getOutputStream().println(LINE);
						response.getOutputStream().println(key);
						response.getOutputStream().println(LINE);
						response.getOutputStream().println(
								Arrays.toString(errors.get(key)));
					}
					response.getOutputStream().flush();
				} catch (Exception e) {
					Throwable cause = ExceptionUtil.getRootCause(e);
					response.getOutputStream().write(
							cause.getMessage().getBytes());
					response.getOutputStream().flush();
				}
			}

			response.getOutputStream().println("Completed: " + new Date());
			response.getOutputStream().flush();
		} catch (Exception e) {
			log(e.getMessage(), e);
			Throwable cause = ExceptionUtil.getRootCause(e);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
					cause.getMessage());
		}
	}
}
